﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Classes;
using VAdvantage.Utility;
using VAdvantage.Model;
using System.Data;
using VAdvantage.DataBase;
using VAdvantage.Apps;
using System.Collections.Generic;
using System.Threading;
using System.IO;
using System.Windows.Threading;
using VAdvantage.Controls;
using System.ComponentModel;
using SL4PopupMenu;
using VAdvantage.DSProcessWorkflow;

namespace VAdvantage.Print
{
    public class AReport
    {
        public AReport()
        {
        }

        APanel mApanel = null;
        string fileName = "";
        //string clickedMenu = null;
        KeyNamePair pp = null;

        public AReport(int AD_Table_ID, ToolBarButton sender, Query query, APanel _aPanel)
        {
            //pp = panelPP;
            //_list = _panelList;
            //clickedMenu = _clickedMenu;
            mApanel = _aPanel;
            _query = query;
            GetPrintFormats(AD_Table_ID, sender);
        }

        /**	The Query						*/
        private Query _query;

        /// <summary>
        /// Creates the new format
        /// </summary>
        /// <param name="AD_Table_ID">table id</param>
        private void CreateNewFormat(int AD_Table_ID)
        {
            MPrintFormat pf = MPrintFormat.CreateFromTable(Envs.GetContext(), AD_Table_ID);
            LaunchReport(pf);
        }	//	createNewFormat

        //saves the list
        private List<KeyNamePair> _list = new List<KeyNamePair>();


        /// <summary>
        /// Get the Print Formats for the table.
        /// Fill the list and the popup menu
        /// </summary>
        /// <param name="AD_Table_ID">table</param>
        public void GetPrintFormats(int AD_Table_ID, ToolBarButton sender)
        {
            int AD_Client_ID = Envs.GetContext().GetAD_Client_ID();

            String sql = MRole.GetDefault().AddAccessSQL(
                "SELECT AD_PrintFormat_ID, Name, AD_Client_ID "
                    + "FROM AD_PrintFormat "
                    + "WHERE AD_Table_ID='" + AD_Table_ID + "' AND IsTableBased='Y' "
                    + "ORDER BY AD_Client_ID DESC, IsDefault DESC, Name",		//	Own First
                "AD_PrintFormat", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);

            KeyNamePair pp = null;

            IDataReader dr = DB.ExecuteReader(sql);
            try
            {

                int counter = 0;
                while (dr.Read())
                {
                    pp = new KeyNamePair(Util.GetValueOfInt(dr[0].ToString()), dr[1].ToString());
                    if (Utility.Util.GetValueOfInt(dr[2].ToString()) == AD_Client_ID)
                    {
                        counter++;
                        _list.Add(pp);
                        String actionCommand = pp.ToString();
                    }
                }
                dr.Close();
            }
            catch (Exception sqle)
            {
            }

            if (_list.Count == 0)
            {
                if (pp == null)
                    LaunchReport(null, AD_Table_ID);		//	calls launch
                else
                    LaunchReport(pp, AD_Table_ID);	
            }
            //	One Format exists or no invoker - show it
            else
            {
                LaunchReport(_list[0], 0);
                //for (int i = 0; i < _list.Count; i++)
                //{
                //    KeyNamePair newpp = (KeyNamePair)_list[i];
                //    if (clickedMenu == newpp.GetName())
                //    {
                //        LaunchReport(newpp, 0);
                //        return;
                //    }
                //}
            }
        }

        void mnu_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < _list.Count; i++)
            {
                KeyNamePair pp = (KeyNamePair)_list[i];
                if ((sender as PopupMenuItem).Header.ToString() == pp.GetName())
                {
                    LaunchReport(pp, 0);
                    return;
                }
            }
        }


        byte[] pdfBytes = null;

        public byte[] PdfBytes
        {
            get { return pdfBytes; }
            set { pdfBytes = value; }
        }


        FileStream pdfStream = null;

        public FileStream PdfStream
        {
            get { return pdfStream; }
            set { pdfStream = value; }
        }

        ReportInfo rep = null;

        public ReportInfo ReportPdfInfo
        {
            get { return rep; }
            set { rep = value; }
        }

        /// <summary>
        /// Launch Report
        /// </summary>
        /// <param name="pp">KeyNamePair values</param>
        private void LaunchReport(KeyNamePair pp, int AD_Table_ID)
        {
            
            bool pass = false;
            var client = AEnv.GetDSPWFClient();
            client.GeneratePdfReportCompleted += (ov, ev) =>
            {
                if (ev.Result != null)
                {
                    //string fileName = _query.GetTableName().Replace(" ", "_");

                    try
                    {
                        ReportPdfInfo = ev.Result;

                    }
                    catch (Exception ex)
                    {
                    }

                }
                pass = true;

            };


            List<string> queryInfo = new List<string>();
            queryInfo.Add(_query.GetTableName());
            queryInfo.Add(_query.GetWhereClause(true));

            Ctx ctx = Envs.GetCtx();
            Dictionary<string, string> dic = (Dictionary<String, string>)ctx.GetMap();
            client.GeneratePdfReportAsync(dic, pp == null ? AD_Table_ID : pp.GetKey(), queryInfo, _query.GetCode(0), (AD_Table_ID > 0), null);
            client.CloseAsync();

            while (!pass)
            {
                Thread.Sleep(0);
            }
        }	//	launchReport


        void Execute(KeyNamePair pp, int AD_Table_ID)
        {
            bool pass = false;
            var client = AEnv.GetDSPWFClient();
            client.GeneratePdfReportCompleted += (ov, ev) =>
            {
                if (ev.Result != null)
                {
                    //string fileName = _query.GetTableName().Replace(" ", "_");

                    try
                    {
                        ReportPdfInfo = ev.Result;

                    }
                    catch (Exception ex)
                    {
                    }

                }
                pass = true;

            };


            List<string> queryInfo = new List<string>();
            queryInfo.Add(_query.GetTableName());
            queryInfo.Add(_query.GetWhereClause(true));

            Ctx ctx = Envs.GetCtx();
            Dictionary<string, string> dic = (Dictionary<String, string>)ctx.GetMap();
            client.GeneratePdfReportAsync(dic, pp == null ? AD_Table_ID : pp.GetKey(), queryInfo, _query.GetCode(0), (AD_Table_ID > 0), null);
            client.CloseAsync();

            while (!pass)
            {
                Thread.Sleep(0);
            }

            return;
        }

        /// <summary>
        /// Launch Report
        /// </summary>
        /// <param name="pf">PrintFormat Object</param>
        private void LaunchReport(MPrintFormat pf)
        {
            //Code to preload the format (not include as user can change setting at the last moment )
            int Record_ID = 0;
            if (_query.GetRestrictionCount() == 1 && (_query.GetCode(0)).GetType() == typeof(int))
                Record_ID = ((int)_query.GetCode(0));
            PrintInfo info = new PrintInfo(pf.GetName(), pf.GetAD_Table_ID(), Record_ID);
            info.SetDescription(_query.GetInfo());

            //ReportEngine re = new ReportEngine(Envs.GetContext(), pf, _query, info);
        }	//	launchReport


        void view_Closed(object sender, EventArgs e)
        {
            mApanel.SetBusy(false, false);
        }	//	launchReport
    }
}
